/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.nii.qlks.DataAccessLayer;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.*;

/**
 *
 * @author MARS_NHO
 */
public class MSSQLConnect extends BaseSQLConnect {

    int Port = 0;

    // Ham khoi tao vaf truyen thong tin cua DataBase Server
    public MSSQLConnect(String Host, int Port, String UserName, String Password, String DataBase) {
        this.Host = Host;
        this.Port = Port;
        this.UserName = UserName;
        this.Password = Password;
        this.DataBase = DataBase;
    }

    // Ham kiem tra xem Driver connect Access da san sang hay chua?
    protected void driverTest() throws Exception {
        try {
            // Kiem tra Class.Name
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } // Neu chua ton tai thi nem loi ra ngoai
        catch (ClassNotFoundException e) {
            throw new Exception("Access JDBC Driver not found.");
        }
    }

    // Ham lay Connection
    public Connection getConnect() throws Exception {
        //Neu connection null thi khoi tao moi
        if (this.connect == null) {
            //Kiem tra Driver
            driverTest();

            // Tao Url ket noi den DataBase Server
            String url = "jdbc:odbc:" + this.DataBase;
            try {
                // Tao Connection thong qua url
                //this.connect = DriverManager.getConnection(url, this.UserName, this.Password);

                SQLServerDataSource ds = new SQLServerDataSource();
                ds.setUser(this.UserName);
                ds.setPassword(this.Password);
                ds.setServerName(this.Host);

                ds.setPortNumber(this.Port);
                ds.setDatabaseName(this.DataBase);

                this.connect = ds.getConnection();
            } // Neu khong thanh cong nem loi ra ngoai
            catch (SQLException e) {
                throw new Exception("Khong the ket noi den DataBase Server " + url + e.getMessage());
            }
        }

        // Tra connection ra ngoai
        return this.connect;
    }
}
